//
//  XDTools.m
//  XDBaseFrameWork
//
//  Created by XD-XY on 9/18/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "XDTools.h"

@implementation XDTools

DEFINE_SINGLETON_FOR_CLASS(XDTools)

//获取Appdelegate 指针
+ (AppDelegate *)appDelegate
{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

//jsonkit 解析json格式
+ (NSDictionary *)JSonFromString:(NSString* )result
{
    NSDictionary *json = [result objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
    return json;
    
}

//显示指示器
+ (void)showProgress:(UIView *) view
{
    [MBProgressHUD showHUDAddedTo:view animated:YES];
}

//显示指示器和文字
+ (void)showProgress:(UIView *) view showText:(NSString*)text
{
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.labelText = text;
}

//显示指示器文字
+ (void) showTips:(NSString *)text toView:(UIView *)view
{
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
	hud.mode = MBProgressHUDModeText;
	hud.labelText = text;
	[hud show:YES];
	[hud hide:YES afterDelay:1];
}

//显示成功标识指示器和文字以及自定义图片
+ (void)showSuccessTips:(NSString *)text image:(UIImage *)image toView:(UIView *)view
{
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.backgroundColor = [UIColor clearColor];
    hud.mode = MBProgressHUDModeCustomView;
    hud.color = [UIColor clearColor];
    hud.customView = [[UIImageView alloc] initWithImage:image];
    [hud show:YES];
    [hud hide:YES afterDelay:1];
}

//显示失败标识指示器和文字
+ (void)showErrorTips:(NSString *)text toView:(UIView *)view
{
    
}

//隐藏指示器
+ (void)hideProgress:(UIView *)view
{
    [MBProgressHUD hideAllHUDsForView:view animated:YES];
}

//将字典、数组转换成json串
+(NSString *)stringFromObject:(id)obj{
    return [obj JSONString];
}

//将json串反解析
+(id)objectFromString:(NSString *)str{
    
    return [str objectFromJSONString];
}

//获取uuid
-(NSString *)gen_uuid
{
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
    
    CFRelease(uuid_ref);
    NSString * uuid = [NSString stringWithString:(__bridge NSString*)uuid_string_ref];
    
    CFRelease(uuid_string_ref);
    return uuid;
}

//判断当前时间和过去时间的时间差
- (NSString *)intervalSinceNow:(NSString *) theDate
{
    if (!IS_NOT_EMPTY(theDate)){
        return nil;
    }
    if (theDate.length !=19){
        return @"时间格式错误";
    }
    NSString *yearStr = [theDate substringToIndex:4];
    
    
    NSDateFormatter *date=[[NSDateFormatter alloc] init];
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString *timeString=@"";
    
    NSString *nowTime = [NSString stringWithFormat:@"%@",
                         [date stringFromDate:[NSDate date]]];
    NSString *nowYear = [nowTime substringToIndex:4];
    
    if (![nowYear isEqualToString:yearStr]) {   //不是今年，显示完整时间
        return [theDate substringToIndex:11];
    }
    
    NSString * str1 = [theDate substringWithRange:NSMakeRange(8, 2)];
    NSString * str2 = [nowTime substringWithRange:NSMakeRange(8, 2)];
    if ([str2 compare:str1]==0){        //今天显示时分秒
        timeString = [theDate substringWithRange:NSMakeRange(11, 5)];
    }else{                              //过去显示月日
        timeString = [theDate substringWithRange:NSMakeRange(5, 11)];
    }
    
    return timeString;
}

+(void)moveFileToDocument:(NSString *)name andType:(NSString *)type
{
    //1.获取文件在工程中的路径--源路径
    NSString * sourcesPath = [[NSBundle mainBundle] pathForResource:name ofType:type];
    
    //2.获取沙盒中Document文件夹的路径--目的路径
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * documentPath = [paths objectAtIndex:0];
    NSString * desPath = [documentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",name,type]];
    DDLOG(@"desPath = %@",desPath);
    //3.通过NSFileManager类，将工程中的数据库文件复制到沙盒中。
    NSFileManager * fileManager  =[NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:desPath]){
        NSError * error;
        if ([fileManager copyItemAtPath:sourcesPath toPath:desPath error:&error]){
            DDLOG(@"文件移动成功");
        }else{
            DDLOG(@"文件移动失败");
        }
    }else{
        DDLOG(@"文件已存在");
    }
}

//Label自适应大小
+(CGRect )autoSizeOfWidget:(UILabel *)widget andSize:(CGSize)size andtextFont:(CGFloat )sizefont
{
    widget.numberOfLines = 0;
    CGRect rect = widget.frame;
    if ([widget.text length]==0){
        return CGRectMake(rect.origin.x, rect.origin.y, 0, 0);
    }
    if (IOS7){
        NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:sizefont],NSFontAttributeName,nil];
        CGSize  actualsize =[widget.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin  attributes:tdic context:nil].size;
        CGRect tmpRect = CGRectMake(rect.origin.x, rect.origin.y, actualsize.width, actualsize.height);
        return tmpRect;
    }else{
        CGSize strSize = [widget.text sizeWithFont:[UIFont systemFontOfSize:sizefont] constrainedToSize:size lineBreakMode:NSLineBreakByCharWrapping];
        CGRect tmpRect = CGRectMake(rect.origin.x, rect.origin.y, strSize.width, strSize.height);
        return tmpRect;
    }
}

//计算文字宽和长
+(CGRect)autoSizeOftext:(NSString *)text andSize:(CGSize)size andtextFont:(CGFloat)sizefont
{
    if (text == nil) {
        text = @"";
    }
    if (IOS7){
        NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:sizefont],NSFontAttributeName,nil];
        CGSize  actualsize =[text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin  attributes:tdic context:nil].size;
        CGRect tmpRect = CGRectMake(0, 0, actualsize.width, actualsize.height);
        return tmpRect;
    }else{
        CGSize strSize = [text sizeWithFont:[UIFont systemFontOfSize:sizefont] constrainedToSize:size lineBreakMode:NSLineBreakByCharWrapping];
        CGRect tmpRect = CGRectMake(0, 0, strSize.width, strSize.height);
        return tmpRect;
    }
}


//图片无损拉伸
+(UIImage *)stretchableImag:(UIImage *)image
{
    image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(2,2,2,2)];
    return image;
}

//获取数据库指针
+(FMDatabase*)getDb{
    //paths： ios下Document路径，Document为ios中可读写的文件夹
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    //dbPath： 数据库路径，在Document中。
    NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"area.db"];
    //创建数据库实例 db  这里说明下:如果路径中不存在"Test.db"的文件,sqlite会自动创建"Test.db"
    FMDatabase * db = [FMDatabase databaseWithPath:dbPath] ;
    return db;
}

//GET 请求 获取数据
+ (ASIHTTPRequest*)getRequestWithDict:(NSDictionary *)dict API:(NSString *)api
{
    NSMutableDictionary *muDict = [[NSMutableDictionary alloc] initWithDictionary:dict];
    NSMutableString *params = [[NSMutableString alloc] init];
    for (id keys in muDict) {
        [params appendFormat:@"&%@=%@",keys,[muDict objectForKey:keys]];
    }
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@%@",HOST_URL,api,params];
    DDLOG(@"%@",urlStr);
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL:url];
    [request setTimeOutSeconds:15];
    
    [request setRequestCookies:nil];
    [request setUseCookiePersistence:NO];
    
    return request;
}

//POST 请求 获取数据
+ (ASIFormDataRequest*)postRequestWithDict:(NSDictionary *)dict API:(NSString *)api
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST_URL,api]];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    NSMutableDictionary *muDict = [[NSMutableDictionary alloc] initWithDictionary:dict];
    
    [request setRequestMethod:@"POST"];
    [request setTimeOutSeconds:15];
    for (id key in muDict) {
        [request setPostValue:[muDict objectForKey:key] forKey:key];
    }
    
    if (ISLOGING) {
        [request setPostValue:[[NSUserDefaults standardUserDefaults] objectForKey:kMY_USER_ID] forKey: @" CustomerID"];
    }
    
    DDLOG(@"post muDict :%@", muDict);
    DDLOG(@"post muDict :%@", url);
    [request setUseCookiePersistence:NO];
    [request setUserAgentString:@"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"];
    return request;
}

//POST 请求 上传文件
+ (ASIFormDataRequest*)postRequestWithDict:(NSDictionary *)dict API:(NSString *)api  fileName:(NSString *)filename  fileData:(NSData *)data
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST_URL,api]];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    NSMutableDictionary *muDict = [[NSMutableDictionary alloc] initWithDictionary:dict];
    
    [request setRequestMethod:@"POST"];
    [request setTimeOutSeconds:15];
    for (id key in muDict) {
        [request setPostValue:[muDict objectForKey:key] forKey:key];
    }
    [request addData:data withFileName:filename andContentType:@"image/jpeg" forKey:@"img"];
    
    DDLOG(@"post muDict :%@", muDict);
    
    [request setUseCookiePersistence:NO];
    [request setUserAgentString:@"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"];
    return request;
}

//判断有无网络
+(BOOL)NetworkReachable
{
    NetworkStatus wifi = [[Reachability reachabilityForLocalWiFi] currentReachabilityStatus];
    NetworkStatus gprs = [[Reachability reachabilityForInternetConnection] currentReachabilityStatus];
    if(wifi == NotReachable && gprs == NotReachable)
    {
        return NO;
    }
    return YES;
}

//计算缓存
-(void)CalculateTheCache:(UILabel *)label
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        int size = [self sizeOfFolder:[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
        NSString * lastSize = @"";
        if (size < (1024*1024)) {
            lastSize = [NSString stringWithFormat:@"%.1fKB",size/1024.0f];
        }else if(size > (1024*1024)){
            lastSize = [NSString stringWithFormat:@"%.1fMB",size/1024.0f/1024.0f];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            label.text = lastSize;
        });
    });
}

- (int)sizeOfFolder:(NSString*)folderPath
{
    NSArray *contents;
    NSEnumerator *enumerator;
    NSString *path;
    contents = [[NSFileManager defaultManager] subpathsAtPath:folderPath];
    enumerator = [contents objectEnumerator];
    int fileSizeInt = 0;
    while (path = [enumerator nextObject]) {
        NSError *error;
        NSDictionary *fattrib = [[NSFileManager defaultManager] attributesOfItemAtPath:[folderPath stringByAppendingPathComponent:path] error:&error];
        fileSizeInt +=[fattrib fileSize];
    }
    return fileSizeInt;
}

//清理缓存
-(void)clearTheCache:(UILabel *)label
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        
        NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
//        NSLog(@"files :%d",[files count]);

        for (NSString *p in files) {
            NSError *error;
            NSString *path = [cachPath stringByAppendingPathComponent:p];
            if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            label.text=@"0KB";
            
        });
    });
}

//创建cell的分割线
-(UIView *)createSeparatorLineWithRect:(CGRect)rect
{
    UIView * view = [[UIView alloc] initWithFrame:rect];
    view.backgroundColor = RGBA(200, 200, 200, 1);
    return view;
}

//打电话
+(void)MakeAPhoneCall
{
    NSString * num = [[NSString alloc] initWithFormat:@"tel://%@",@"4008186060"];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:num]];
}

//编辑字符串颜色，大小
+(NSMutableAttributedString *)getAcolorfulStringWithTextArray:(NSArray *)array Color:(UIColor *)color Font:(UIFont *)font AllText:(NSString *)allText
{
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:allText];
    [str beginEditing];

    for (NSString * string in array) {
        if (str.length) {
            NSRange range1 = [allText rangeOfString:string];
            [str addAttribute:(NSString *)(NSForegroundColorAttributeName) value:color range:range1];
            if (font) {
                [str addAttribute:NSFontAttributeName value:font range:range1];
            }
        }
    }


    [str endEditing];

    return str;
}
+(BOOL)chickIphoneNumberRight:(NSString *)str
{
    NSString *regex = @"^((13[0-9])|(147)|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:str];
    return isMatch;
    
}


////上传头像
+ (ASIFormDataRequest*)postRequestWithDict:(NSDictionary *)dict API:(NSString *)api data:(NSData *)data
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST_URL,api]];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    NSMutableDictionary *muDict = [[NSMutableDictionary alloc] initWithDictionary:dict];
    
    [request setRequestMethod:@"POST"];
    [request setTimeOutSeconds:15];
    for (id key in muDict) {
        [request setPostValue:[muDict objectForKey:key] forKey:key];
    }
    [request addData:data withFileName:@"KKK" andContentType:@"image/jpeg" forKey:@"img"];
    
    DDLOG(@"post muDict :%@", muDict);
    
    
    return request;
}

+ (NSMutableArray *)getArrayWithKey:(NSString *)key table:(NSString *)table
{
    NSMutableArray * array = [[NSMutableArray alloc] init];
    FMDatabase * db = [XDTools getDb];
    if (![db open]){
        DDLOG(@"open fail!");
        return nil;
    }
    NSString * queryString = @"";
    NSString * returenStr = @"";
    NSString * parentID = @"";



    if (key) {

        if ([table isEqualToString:@"city"]) {

            FMResultSet * rs = [db executeQuery:@"SELECT * FROM provience WHERE name = ?",key];

            while ([rs next]) {
                parentID = [rs objectForColumnName:@"id"];
            }
        }else if ([table isEqualToString:@"area"]) {

            FMResultSet * rs = [db executeQuery:@"SELECT * FROM city WHERE name = ?",key];

            while ([rs next]) {
                parentID = [rs objectForColumnName:@"id"];
            }
        }

        queryString = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE parentid = %@",table,parentID];

        FMResultSet * rs = [db executeQuery:queryString];

        while ([rs next]) {
            returenStr = [rs objectForColumnName:@"name"];
            [array addObject:returenStr];
        }
    }else {

        queryString = [NSString stringWithFormat:@"SELECT * FROM %@",table];

        FMResultSet * rs = [db executeQuery:queryString];

        while ([rs next]) {
            returenStr = [rs objectForColumnName:@"name"];
            [array addObject:returenStr];
        }

    }
    
    [db close];
    
    return array;
    
}


//转换接片量为等级
+ (NSInteger)changeOrderCountToLevel:(NSInteger)orderCount
{
    NSInteger num = 0;
    if (orderCount >= 2 && orderCount <= 5) {
        num += 1;
    }
    if (orderCount >= 6 && orderCount <= 10) {
        num += 2;
    }
    if (orderCount >= 11 && orderCount <= 20) {
        num += 3;
    }
    if (orderCount >= 21 && orderCount <= 30) {
        num += 4;
    }
    if (orderCount >= 31 && orderCount <= 50) {
        num += 5;
    }
    if (orderCount >= 51 && orderCount <= 70) {
        num += 6;
    }
    if (orderCount >= 71 && orderCount <= 100) {
        num += 7;
    }
    if (orderCount >= 101 && orderCount <= 140) {
        num += 8;
    }
    if (orderCount >= 141 && orderCount <= 200) {
        num += 9;
    }
    if (orderCount >= 201 && orderCount <= 300) {
        num += 10;
    }
    if (orderCount >= 301 && orderCount <= 450) {
        num += 11;
    }
    if (orderCount >= 451 && orderCount <= 600) {
        num += 12;
    }
    if (orderCount >= 601 && orderCount <= 800) {
        num += 13;
    }
    if (orderCount >= 801 && orderCount <= 1000) {
        num += 14;
    }
    if (orderCount >= 1001 && orderCount <= 1250) {
        num += 15;
    }
    if (orderCount >= 1251 && orderCount <= 1500) {
        num += 16;
    }
    if (orderCount >= 1501 && orderCount <= 1800) {
        num += 17;
    }
    if (orderCount >= 1801 && orderCount <= 2150) {
        num += 18;
    }
    if (orderCount >= 2151 && orderCount <= 2500) {
        num += 19;
    }
    if (orderCount >= 2501 && orderCount <= 3000) {
        num += 20;
    }
    if (orderCount >= 3001 && orderCount <= 3500) {
        num += 21;
    }
    if (orderCount >= 3501 && orderCount <= 4000) {
        num += 22;
    }
    if (orderCount >= 4001 && orderCount <= 4500) {
        num += 23;
    }
    if (orderCount >= 4501 && orderCount <= 5000) {
        num += 24;
    }
    return num;
}

//-(BOOL)haveYouHuiQuan
//{
//    return [self getDataWithDict:@{@"CustomerID":[[NSUserDefaults standardUserDefaults] objectForKey:kMY_USER_ID] } api:API_GETYOUHUIQUAN];
//    
//}

-(BOOL)getDataWithDict:(NSDictionary *)dict api:(NSString *)api
{
    __block BOOL result = NO;
    if (![XDTools NetworkReachable]) {
        return result;
    }
    
    __weak ASIHTTPRequest *request = [XDTools postRequestWithDict:dict API:api];
    [request setCompletionBlock:^{
        
        NSDictionary *tempDic = [XDTools  JSonFromString:[request responseString]];
        
        DDLOG(@"temdic = %@",tempDic);
        
        if([[tempDic objectForKey:@"status"]intValue] == 1){
            NSArray * dataArray = tempDic[@"data"];
            for (NSDictionary * dic in dataArray) {
                if ([[dic objectForKey:@"status"]integerValue] == 2) {
                    result = YES;
                }
            }
        }
    }];
    
    [request setFailedBlock:^{
        
    }];
    [request startAsynchronous];
    
    return result;
}



@end
